import { TaHttp } from "../script/ajax"
import { TaCache } from "../script/tools"

export const TaWxapp = {
	// 微信小程序登录
	login(): Promise<any> {
		return new Promise((resolve, reject) => uni.login({
			provider: 'weixin', success(loginRes: any) {
				// 换取会话密钥
				let data = { code: loginRes.code, iv: '', encrypted: '' }
				TaHttp.post('/plugin-account/api.wxapp/session', data).then((ret: any) => {
					console.log('SessionDone: ', ret)
					TaCache.set('auth.token', ret.data.token)
					// 获取用户信息
					uni.getUserInfo({
						provider: 'weixin',
						success: (infoRes: any) => {
							console.log('UserInfo: ', infoRes)
							data.iv = infoRes.iv, data.encrypted = infoRes.encryptedData
							TaHttp.post('/plugin-account/api.wxapp/decode', data).then((ret: any) => {
								console.log('UserDone: ', ret.data)
								resolve(ret.data)
							}).catch((ret: any) => {
								console.log('UserFail: ', ret.data)
								reject(ret)
							})
						}
					})
				}).catch((ret: any) => {
					console.log('SessionFail: ', ret)
					reject(ret);
				})
			}
		}))
	}
}